package com.whjfxx.terminal.biz.service.impl;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.whjfxx.terminal.biz.service.CaptchaService;
import com.whjfxx.terminal.utils.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by b.c on 2022/6/24 13:41
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {

    final static int LEN = 4;

    @Override
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        this.spec(request, response);
    }

    @Override
    public void spec(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uuid = request.getParameter("timestamp");
        if (StringUtils.isBlank(uuid)) {
            return;
        }
        ServletOutputStream outputStream = response.getOutputStream();
        SpecCaptcha captcha = new SpecCaptcha(120, 40);
        captcha.setLen(LEN);
        String code = captcha.text();
        RedisUtil.set(uuid, code, 2 * 60);
        captcha.out(outputStream);
    }

    @Override
    public void gif(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uuid = request.getParameter("timestamp");
        if (StringUtils.isBlank(uuid)) {
            return;
        }
        ServletOutputStream outputStream = response.getOutputStream();
        GifCaptcha captcha = new GifCaptcha(120, 40);
        captcha.setLen(LEN);
        String code = captcha.text();
        RedisUtil.set(uuid, code, 2 * 60);
        captcha.out(outputStream);
    }

    @Override
    public void chinese(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uuid = request.getParameter("timestamp");
        if (StringUtils.isBlank(uuid)) {
            return;
        }
        ServletOutputStream outputStream = response.getOutputStream();
        ChineseCaptcha captcha = new ChineseCaptcha(120, 40);
        captcha.setLen(LEN);
        String code = captcha.text();
        RedisUtil.set(uuid, code, 2 * 60);
        captcha.out(outputStream);
    }

    @Override
    public void arithmetic(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String uuid = request.getParameter("timestamp");
        if (StringUtils.isBlank(uuid)) {
            return;
        }
        ServletOutputStream outputStream = response.getOutputStream();
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(120, 40);
        captcha.setLen(LEN);
        String code = captcha.text();
        RedisUtil.set(uuid, code, 2 * 60);
        captcha.out(outputStream);
    }
}
